/*
 * Copyright 2016-2036 the original author or authors.
 * 
 * COMMERCIAL USE OF THIS SOFTWARE WITHOUT WARRANTY IS NOT ALLOWED.
 * Use is subject to license terms! You can distribute a copy of this software
 * to others for free. This software is a non-profit and open-source project.
 * Any contribution to this project will make it better.
 * All rights reserved! Owned by Stephen Liu.
 * 
 */
package com.github.raffle.concurrent;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author ste7en.liu@gmail.com
 * @since 2016/12/4
 */
public class ClhLock {

    private AtomicReference<Node> tail;

    private ThreadLocal<Node> prev;
    private ThreadLocal<Node> node;

    public ClhLock() {
        tail = new AtomicReference<>(new Node());
        node = new ThreadLocal<>();
        node.set(new Node());

        prev = new ThreadLocal<>();
    }

    public void lock() {

        Node myNode = node.get();
        myNode.locked = true;
        Node myPrev = tail.getAndSet(myNode);
        prev.set(myPrev);
        while (myPrev.locked) {
            //
        }

    }

    public void unlock() {
        Node myNode = node.get();
        myNode.locked = false;
        node.set(prev.get());

    }

    class Node {
        boolean locked = true;
    }
}
